/* eslint-disable */
const NEED_ANYCHAT_APILEVEL = '0'
const GV_ERR_ALREADY_LOGIN = 201
let anychatIsReady = false
// anychatSDK
let anychatSDKIsReady = false
const loadAnychatSDK = () => {
  const staticPath = '/static/'
  return new Promise(resolve => {
    if (!anychatSDKIsReady) {
      const anychat4html5 = document.createElement('script')
      anychat4html5.setAttribute('id', 'anychat4html5')
      anychat4html5.type = 'text/javascript'
      document.body.appendChild(anychat4html5)
      anychat4html5.src = staticPath + 'js/anychat/anychat4html5.min.js'
      anychat4html5.onload = () => {
        const anychatobject = document.createElement('script')
        anychatobject.setAttribute('id', 'anychatobject')
        anychatobject.type = 'text/javascript'
        document.body.appendChild(anychatobject)
        anychatobject.src = staticPath + 'js/anychat/anychatobject.js'
        anychatobject.onload = () => {
          const anychatsdk = document.createElement('script')
          anychatsdk.setAttribute('id', 'anychatsdk')
          document.body.appendChild(anychatsdk)
          anychatsdk.src = staticPath + 'js/anychat/anychatsdk.js'
          anychatsdk.onload = () => {
            const anychatevent = document.createElement('script')
            anychatevent.setAttribute('id', 'anychatevent')
            document.body.appendChild(anychatevent)
            anychatevent.src = staticPath + 'js/anychat/anychatevent.js'
            anychatevent.onload = () => {
              setTimeout(() => {
                anychatSDKIsReady = true
                resolve()
              }, 1000)
            }
          }
        }
      }
    } else {
      resolve()
    }
  })
}
const initSdkAndConnect = ({ appKey }, callback) => {
  if (!anychatIsReady) {
    if (navigator.plugins && navigator.plugins.length) {
      window.navigator.plugins.refresh(false)
    }
    const initSdkCode = BRAC_InitSDK(NEED_ANYCHAT_APILEVEL)
    // BRAC_SetSDKOption(BRAC_SO_CLOUD_APPGUID, appKey)
    if (initSdkCode === GV_ERR_SUCCESS) {
      BRAC_SetSDKOption(BRAC_SO_CLOUD_APPGUID, appKey)
      const connectCode = BRAC_Connect('cloud.anychat.cn', '8906')
      if (connectCode === GV_ERR_SUCCESS) {
        BRAC_SetSDKOption(BRAC_SO_VIDEOSHOW_CLIPMODE, 2)
        anychatIsReady = true
        callback()
      } else {
        setTimeout(() => {
          initSdkAndConnect({ appKey }, callback)
        }, 1000)
      }
    } else {
      if (
        initSdkCode === GV_ERR_PLUGINNOINSTALL ||
        initSdkCode === GV_ERR_PLUGINOLDVERSION
      ) {
        rootVm.$alert(
          '首次进入需要安装插件或者当前插件的版本过低，请点击“下载插件”按钮进行安装，安装完成后请重启浏览器！',
          '下载插件提示',
          {
            type: 'error',
            showClose: false,
            closeOnClickModal: false,
            confirmButtonText: '下载插件',
            callback: action => {
              window.open(
                'http://anychat.oss-cn-hangzhou.aliyuncs.com/AnyChatWebSetup.exe'
              )
            }
          }
        )
      } else {
        setTimeout(() => {
          initSdkAndConnect({ appKey }, callback)
        }, 1000)
      }
    }
  } else {
    callback()
  }
}
function isIE() {
  const userAgent = window.navigator.userAgent.toLowerCase()
  return userAgent.match(/msie/) != null || userAgent.match(/trident/) != null
}

export default {
  install(Vue, options) {
    Vue.prototype.anychat = {
      init: function(params) {
        return new Promise((resolve, reject) => {
          if (isIE()) {
            loadAnychatSDK().then(() => {
              initSdkAndConnect(params, resolve)
            })
            // initSdkAndConnect(params, resolve)
          } else {
            resolve()
          }
        })
      }, // open: 1打开，0关闭
      controlCamera: function(userId, open = 1) {
        if (isIE()) {
          const cameraCode = BRAC_UserCameraControl(userId, open)
        }
      }, // open: 1打开，0关闭
      controlSpeak: function(userId, open = 1) {
        if (isIE()) {
          const speakCode = BRAC_UserSpeakControl(userId, open)
        }
      },
      controlCameraAndSpeak: function(userId, open = 1) {
        this.controlCamera(userId, open)
        this.controlSpeak(userId, open)
      },
      setVideoPos: function(userId, element) {
        if (isIE()) {
          BRAC_SetVideoPos(
            userId,
            document.getElementById(element),
            `${element}_obj`
          )
          BRAC_GetDmoObject(`${element}_obj`).SetBkImage(
            process.env.VUE_APP_OSS_SERVER_URL + '/common/anychatbg.jpg'
          )
        }
      },
      enterRoom: function(roomId) {
        return new Promise((resolve, reject) => {
          if (isIE()) {
            const enterCode = BRAC_EnterRoom(roomId, '', 0)
            if (enterCode === -1 || enterCode === GV_ERR_SUCCESS) {
              setTimeout(() => {
                resolve()
              }, 1000)
            } else {
              reject()
            }
          } else {
            resolve()
          }
        })
      },
      leaveRoom: function(roomId, userId, targetSelfId) {
        if (isIE()) {
          this.controlCameraAndSpeak(userId, 0)
          this.controlCameraAndSpeak(targetSelfId, 0)
          const leaveRoomCode = BRAC_LeaveRoom(roomId)
        }
      },
      login: function({ nickname, userId, appKey }) {
        return new Promise((resolve, reject) => {
          if (isIE()) {
            this.init({ appKey: appKey }).then(() => {
              const loginCode = BRAC_LoginEx(
                nickname,
                userId,
                '',
                appKey,
                new Date()
                  .getTime()
                  .toString()
                  .substr(0, 10),
                '',
                ''
              )
              if (
                loginCode === GV_ERR_SUCCESS ||
                loginCode === GV_ERR_ALREADY_LOGIN
              ) {
                resolve()
              } else {
                reject()
              }
            })
          } else {
            resolve()
          }
        })
      },
      logout: function() {
        return new Promise((resolve, reject) => {
          if (isIE()) {
            const logoutCode = BRAC_Logout()
            if (logoutCode === GV_ERR_SUCCESS) {
              resolve()
            } else {
              reject()
            }
          } else {
            resolve()
          }
        })
      },
      queryCameraState: function({ userId }) {
        return new Promise((resolve, reject) => {
          const cameraCode = BRAC_GetCameraState(userId)
          resolve({ userId, state: cameraCode })
        })
      },
      sendTextMessage: function({ userId, secret = 0, msg = '' }) {
        return new Promise((resolve, reject) => {
          if (isIE()) {
            const sendMessageCode = BRAC_SendTextMessage(userId, secret, msg)
            if (sendMessageCode === GV_ERR_SUCCESS) {
              resolve()
            } else {
              reject()
            }
          } else {
            resolve()
          }
        })
      },
      release: function() {
        BRAC_Release()
      }
    }
  }
}
